/*
 * 太原学院计算机科学与技术系（C） 版权所有。
 */
package cn.edu.tyu.finance.thingstype.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.tyu.util.DBUtil;
import cn.edu.tyu.util.StringUtil;

/**
 * Servlet implementation class LoginServlet
 */
/**
 * 用户登录
 * @author hujinyu
 *
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    /**
     * 处理网页发来的Get请求
     * @param request 请求对象
     * @param response 响应对象
     */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.接收用户名和密码
		String uname=request.getParameter("username");
		String upsw=request.getParameter("userpsw");
		String upswMD5=StringUtil.getMD5(upsw);
		//2.连接数据库，查询有无此人
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		conn=DBUtil.getConnection();
		try {
			String sql="SELECT*FROM financeuser WHERE username=? AND userpsw=?";
			pstmt=conn.prepareStatement(sql);
			pstmt.setNString(1, uname);
			pstmt.setNString(2, upswMD5);
			rs=pstmt.executeQuery();     //查到一条或者0条
			if(rs.next()) {           //rs表示结果集合
				response.sendRedirect("ok.jsp");
			}else {
				response.sendRedirect("fail.jsp");
			}
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}finally {
			DBUtil.backConn(conn, pstmt, rs);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	/**
     * 处理网页发来的Get请求
     * @param request 请求对象
     * @param response 响应对象
     */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
